﻿(function ($) {

    $.fn.multiImageUploader = function (options) {
        var $uploader = $(this);
        var defaultName = $uploader.find("input[type=hidden]").attr("name");

        var settings = $.extend({
            'uploadUrl': '',
            'disabled': false,
            'accept': "image/*",
            'maxFileSize': 0,
            'width': 120,
            'height': 120,
            'colSize': 3,
            'name': defaultName,
            'cropSize':null
        }, options);

        var __buildNewItem = function (imageUrl, name, width, height, colSize, editEnabled, deletedEnabled) {
            var buttons = "";

            if (editEnabled) {
                buttons += '<button class="btn btn-sm btn-lightyellow editimage" type="button">修改</button>';
                //buttons += '<button class="btn btn-sm btn-danger clearimage" type="button">清除</button>';
            }

            if (deletedEnabled) {
                buttons += '<button class="btn btn-sm btn-lavenderblush deleteimage" type="button">删除</button>';
            }


            var temlpate =
                '<li class="multi-image-uploader-box col-xs-' + colSize + '">' +
                '   <div class="multi-image-uploader-content">' +
                '       <div class="row multi-image-uploader-img"> <div class="multi-image-uploader-img-item" style="width:' + settings.width +'px;height:' + settings.height +'px">' +
                '           <img width="100%" height="100%" src="' + imageUrl + '" />' +
                '           <input type="hidden" name="' + name + '" value="' + imageUrl + '" />' +
                '       </div></div>' +
                '       <div class="row multi-image-uploader-button">' +
                '           <div class="col-xs-12">' +
                '               <button class="btn btn-sm btn-azure viewimage" type="button">查看</button>' +
                buttons +
                '           </div>' +
                '       </div>' +
                '       <div class="clearfix"></div>' +
                '   </div>' +
                '   <div class="clearfix" ></div > ' +
                '</li>';

            return $(temlpate);
        }

        var __refreshItemEvent = function (item) {
            var $item = $(item);
            var viewBtn = $(item).find(".viewimage");
            var editbtn = $(item).find(".editimage");
            var deleteimage = $(item).find(".deleteimage");
            var clearimage = $(item).find(".clearimage");

            var imageUrl = $item.find("input[type=hidden]").val();

            $(viewBtn).click(function () {
                WebUIJS.ShowImageViewer(imageUrl);
            });

            $(editbtn).click(function () {
                if (isEmpty(settings.uploadUrl)) { //如果uploadurl为空,则表示需要使用同步上传
                    var file = $item.find("input[type=file]");

                    if (!file || file.length <= 0) {
                        file = $('<input style="display:none" type="file" name="' + settings.name + '"/>');
                        if (settings.accept && settings.accept !== "") {
                            file.attr("accept", settings.accept);
                        }

                        file[0].onchange = function () {
                            if (this.files.length <= 0) {
                                return false;
                            }

                            if (settings.maxFileSize &&
                                settings.maxFileSize > 0 &&
                                this.files[0].size > settings.maxFileSize) {

                                WebUIJS.Alert("文件太大,不能上传");
                                return false;
                            }

                            try {
                                var reader = new FileReader();
                                reader.onload = function (evt) {
                                    $(item).find("img").attr('src', evt.target.result);
                                }

                                reader.readAsDataURL(this.files[0]);

                            } catch (e) {
                                WebUIJS.Toast("加载图片错误:" + e.message, "error", 2);
                            }
                        }

                        file.insertBefore($item.find("img"));
                    }


                    file.click();
                } else {
                    $.imageUploader({
                        urlOrFile: null,
                        fieldName: settings.name,
                        maxFileSize: settings.maxFileSize,
                        forceCrop: true,
                        cropSize: settings.cropSize,
                        uploadUrl: settings.uploadUrl,
                        onSuccessCallback: function (ret) {
                            if (ret.IsSuccess) {
                                $item.find("img").attr("src", ret.ReturnData);
                                $item.find("input[type=hidden]").val(ret.ReturnData);
                            } else {
                                WebUIJS.Alert(ret.Message);
                            }
                        },
                        onPreview: function (result) {
                            //$(image).attr('src', result.data);
                        },
                        onComplete: function() {
                            $item.find("button").attr("disabled", null); //开始上传完成之后,取消禁用
                        },
                        onBeforeUpload: function() {
                            $item.find("button").attr("disabled", "disabled"); //开始上传之前,禁用按钮
                        }
                    });

                    //WebUIJS.ShowUploadFile(settings.uploadUrl,
                    //    {
                    //        maxFileSize: settings.maxFileSize,
                    //        accept: settings.accept,
                    //        onSuccess: function (ret) {
                    //            if (ret.IsSuccess) {
                    //                $item.find("img").attr("src", ret.ReturnData);
                    //                $item.find("input[type=hidden]").val(ret.ReturnData);
                    //            } else {
                    //                WebUIJS.Alert(ret.Message);
                    //            }
                    //        },
                    //        onCompleted: function () {
                    //            $item.find("button").attr("disabled", null); //开始上传完成之后,取消禁用
                    //        },
                    //        onBeforeUpload: function () {
                    //            $item.find("button").attr("disabled", "disabled"); //开始上传之前,禁用按钮
                    //        },
                    //        onError: function (ret) {
                    //            WebUIJS.Alert(ret.Message);
                    //        }
                    //    });
                }


            });

            $(deleteimage).click(function () {
                $item.remove();
            });

            $(clearimage).click(function () {
                $item.find("img").attr("src", "");
                $item.find("input[type=hidden]").val('');
                if (!settings.uploadUrl || isEmpty(settings.uploadUrl)) {
                    $item.find(":file").remove();
                }

            });

            $item.find("img").on("load", function() {
                var scaleSize = __calcImageSize(
                    this.naturalWidth,
                    this.naturalHeight,
                    $(this).parent().width(),
                    $(this).parent().height());

                this.width = scaleSize.width;
                this.height = scaleSize.height;
            });

        }

        $uploader.find(".addimage").click(function () {
            if (isEmpty(settings.uploadUrl)) {  //如果uploadurl为空,则表示需要使用同步上传
                
                var file = $('<input style="display:none" type="file" name="' + settings.name + '"/>');

                if (settings.accept && settings.accept !== "") {
                    file.attr("accept", settings.accept);
                }

                file[0].onchange = function () {
                    if (this.files.length <= 0) {
                        file.remove();
                        return false;
                    }

                    if (settings.maxFileSize && settings.maxFileSize > 0 && this.files[0].size > settings.maxFileSize) {
                        file.remove();
                        WebUIJS.Alert("文件太大,不能上传");
                        return false;
                    }

                    var item = $uploader.__buildNewItem("",
                        settings.name,
                        settings.width,
                        settings.height,
                        settings.colSize,
                        true,
                        true);

                    file.insertBefore(item.find("img"));

                    try {
                        var reader = new FileReader();
                        reader.onload = function (evt) {
                            $(item).find("img").attr('src', evt.target.result);

                            item.insertBefore($uploader.find(".addimage"));

                            __refreshItemEvent(item);
                        }

                        reader.readAsDataURL(this.files[0]);

                    } catch (e) {
                        //image.attr('src', $(this).val());
                        WebUIJS.Toast("加载图片错误:" + e.message, "error", 2);
                        file.remove();
                        //return;
                    }
                }

                $("body").append(file);

                file.click();
            } else {
                $.imageUploader({
                    urlOrFile: null,
                    fieldName: settings.name,
                    maxFileSize: settings.maxFileSize,
                    forceCrop: true,
                    cropSize: settings.cropSize,
                    uploadUrl: settings.uploadUrl,
                    onSuccessCallback: function (ret) {
                        if (ret.IsSuccess) {
                            var item = __buildNewItem(ret.ReturnData,
                                settings.name,
                                settings.width,
                                settings.height,
                                settings.colSize,
                                true,
                                true);

                            __refreshItemEvent(item);

                            item.insertBefore($uploader.find(".addimage"));
                        } else {
                            WebUIJS.Alert(ret.Message);
                        }
                    },
                    onPreview: function (result) {
                        //$(image).attr('src', result.data);
                    },
                    onAfterSelectFile: function(fileInput) {}
                });


                //WebUIJS.ShowUploadFile(settings.uploadUrl,
                //    {
                //        maxFileSize: settings.maxFileSize,
                //        accept: settings.accept,
                //        onSuccess: function (ret) {
                            

                //        },
                //        onCompleted: function () {

                //        },
                //        onError: function (ret) {
                //            WebUIJS.Alert(ret.Message);
                //        }
                //    });
            }

        });

        var liList = $uploader.find(".multi-image-uploader-box");
        for (var i = 0; i < liList.length; i++) {
            __refreshItemEvent(liList[i]);
        }

    };
})(jQuery);